package cn.gson.springboot.model.service;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;

import cn.gson.springboot.model.dao.AddrecordDAO;
import cn.gson.springboot.model.dao.CkDAO;
import cn.gson.springboot.model.dao.DrugsYkDao;
import cn.gson.springboot.model.dao.GoodAddDAO;
import cn.gson.springboot.model.mapper.RukuMapper;
import cn.gson.springboot.model.pojos.Addrecord;
import cn.gson.springboot.model.pojos.Apply;
import cn.gson.springboot.model.pojos.Applydetai;
import cn.gson.springboot.model.pojos.Ck;
import cn.gson.springboot.model.pojos.DrugsYk;
import cn.gson.springboot.model.pojos.GoodAdd;
import cn.gson.springboot.model.vo.RufangVO;
import cn.gson.springboot.model.vo.SqdrugsVO;

@Service
@Transactional(rollbackFor=Exception.class)
public class RukuService {
	@Autowired
	private RukuMapper tm;
	@Autowired
	private AddrecordDAO am;
	@Autowired
	private GoodAddDAO gm;
	@Autowired
	private DrugsYkDao ddao;
	@Autowired
	private CkDAO ck;
	//查询所有药品
	public List<Map<String,Object>> cxsy() {
		List<Map<String,Object>> ll= tm.cxsy(); 
		return ll;
	}
	//查询所有药品
		public List<Map<String,Object>> sjcx(String a) {
			List<Map<String,Object>> ll= tm.sjcx(a); 
			return ll;
		}
	public List<Map<String,Object>> cxypsy(int a) {
		List<Map<String,Object>> ll= tm.cxypsy(a); 
		return ll;
	}
	
	//申请表主从表添加
		public void saveOrder(RufangVO svo) {
			
			GoodAdd order = svo.getOrder();
			
			GoodAdd save = gm.save(order);
			
			List<Addrecord> details = svo.getDetails();
			//循环
			for (Addrecord pur : details) {
				//添加订单信息
				pur.setGoodAdd(order);
					JSONArray c=ck.kmpccxsy(pur.getDrugsYk().getDrugId(), pur.getDrugPc());
					if(c.size()>0) {
						Ck b=ck.kmcx(pur.getDrugsYk().getDrugId(), pur.getDrugPc());
						b.setDrugs_Stock_kc(b.getDrugs_Stock_kc()+pur.getDrugs_number_xz());
						b.setScTime(pur.getBzq());
						b.setBumenyf(1);
						ck.save(b);
					}else {
						Ck b=new Ck();
						b.setDrugsYk(pur.getDrugsYk());
						b.setDrugs_Stock_kc(pur.getDrugs_number_xz());
						b.setScTime(pur.getBzq());
						b.setDrugsBatchKc(pur.getDrugPc());
						b.setBumenyf(1);
						ck.save(b);
					}
				
				

				
				//查询药品
				DrugsYk drug = ddao.findById(pur.getDrugsYk().getDrugId()).get();
				//重新赋值一下药品对象
				pur.setDrugsYk(drug);
				pur.setDrugs_number_xz(pur.getDrugs_number_xz());
			
				pur.setDrugPc(pur.getDrugPc());
				pur.setDrugTime(pur.getDrugTime());
				pur.setBzq(pur.getBzq());
				am.save(pur);
			}
			//pddao.saveAll(details);
		}
}
